Ext.namespace('wsc');
wsc.info = 'Web SQL Client';
function DataStore(config) {
	var store_data = [];
	if (config.data)
		store_data = config.data;
	var store = {
		_data : store_data,
		data : store_data,
		autoLoad : true,
		proxy : new Ext.data.MemoryProxy(store_data),
		clearData : function() {
			var da = store_data;
			while (da.length > 0)
				da.pop();
		}
	};
	store = Ext.applyIf(store, config);
	store = new Ext.data.SimpleStore(store);
	return store;
}
wsc.Messages = {
		ok: 'OK',
		cancel: 'Cancel',
		infoMessage: 'Info Message',
		fieldRequired: 'Place input field: ',
		configWindowTitle: 'Database Connection Config',
		driverWindowTitle: 'Database Driver Config'
	};
wsc.getWebRoot=function() {
	var path = Ext.BLANK_IMAGE_URL;
	var index = path.indexOf('/script/');
	return path.substring(0, index);
};
wsc.DatebaseDriverWindow = Ext.extend(Ext.Window, {
	title: wsc.Messages.driverWindowTitle,
	modal: true,
	labelAlign:'right',
	buttonAlign: 'center',
	initComponent: function(){
		var t = this;
		t.addEvents('ok','beforeok');
		t.nameId = t.id+'-name';
		t.driverId = t.id+'-driver';
		t.urlId = t.id+'-url';
		t.driverJarLabId = t.id+'-driverJarLab';
		t.formId = t.id+'-form';
		t.items=[{
			id: t.formId,
			width: 400,
			xtype: 'form',
			baseCls : 'x-plain',
			labelAlign:'right',
			buttonAlign: 'center',
			labelWidth: 95,
			bodyStyle: 'padding-top:3px',
			defaults: {xtype:'textfield',anchor:'95%',width:400,allowBlank: false},
			items: [{
				fieldLabel: t.texts.configName,
				name: 'name',
				id: t.nameId
			},{
				fieldLabel: t.texts.driverClass,
				name: 'driver',
				id: t.driverId
			},{
				fieldLabel: t.texts.connectionURL,
				emptyText: '{protocol}{host}{port}{database}',
				name: 'url',
				id: t.urlId
			},{
				fieldLabel: t.texts.driverJarLab,
				name: 'driverJarLab',
				id: t.driverJarLabId,
				xtype: 'fileuploadfield',
				allowBlank: true
			}],
			buttons: [{
				text: wsc.Messages.ok,
				handler: function(b){
					var field = t.checkValues();
					if(!field){
						var vs = t.getValues();
						if(!t.fireEvent('beforeok', t, vs))
							t.fireEvent('ok', t, vs);
					}
				}
			},{
				text: wsc.Messages.cancel,
				handler: function(b){
					t.close();
				}
			}]
		}];
		wsc.DatebaseDriverWindow.superclass.initComponent.call(this);
	},
	checkValues: function(){
		var t = this;
		var form = t.get(t.formId);
		var f = form.get(t.nameId);
		var tmp = f.getValue();
		if(!tmp||tmp.trim()==''){
			Ext.Msg.alert(wsc.Messages.infoMessage, wsc.Messages.fieldRequired+f.fieldLabel);
			return f.name;
		}
		f = form.get(t.driverId);
		tmp = f.getValue();
		if(!tmp||tmp.trim()==''){
			Ext.Msg.alert(wsc.Messages.infoMessage, wsc.Messages.fieldRequired+f.fieldLabel);
			return f.name;
		}
		f = form.get(t.urlId);
		tmp = f.getValue();
		if(!tmp||tmp.trim()==''){
			Ext.Msg.alert(wsc.Messages.infoMessage, wsc.Messages.fieldRequired+f.fieldLabel);
			return f.name;
		}
		return false;
	},
	setValues: function(values){
		if(this.rendered){
			var its = this.get(this.formId).items;
			var count = its.getCount();
			for(var i=0;i<count;i++){
				var it = its.itemAt(i);
				if(it.name&&values[it.name])it.setValue(values[it.name]);
				else if(it.name)it.setValue('');
			}
		}else{
			this.values = values;
			this.on('render',function(p){p.setValues(p.values);delete p.values;},this,{single:true});
		}
	},
	getValues: function(){
		var p = {};
		var its = this.get(this.formId).items;
		var count = its.getCount();
		for(var i=0;i<count;i++){
			var it = its.itemAt(i);
			if(it.name)p[it.name]=it.getValue();
		}
		return p;
	},
	texts: {
		configName: 'Name',
		driverClass: 'Driver Class',
		connectionURL: 'Connectioni URL',
		driverJarLab: 'Driver Jars',
		uploadButtonText: 'Upload'
	}
});
wsc.DatabaseConfigWindow = Ext.extend(Ext.Window, {
	title: wsc.Messages.configWindowTitle,
	modal: true,
	labelAlign:'right',
	buttonAlign: 'center',
	initComponent: function(){
		var t = this;
		t.addEvents('ok');
		t.layout='form';
		t.labelWidth=95;
		t.defaults={xtype:'textfield',anchor:'95%',width:400,allowBlank: false};
		t.items=[{
			fieldLabel: t.texts.configName
		},{
			xtype: 'combo',
			fieldLabel: t.texts.databaseType,
			store: wsc.getDriverStore(t.sqlManager),
			mode: 'local',
			editable: false,
			triggerAction: 'all',
			displayField: 'name',
			valueField: 'driverConfig',
			listeners:{
				select: function(f){
					t.changeDBType(f.getValue());
				}
			}
		},{
			fieldLabel: t.texts.driverClass,
			name: 'driver'
		},{
			fieldLabel: t.texts.host,
			name: 'host'
		},{
			xtype: 'numberfield',
			fieldLabel: t.texts.port,
			name: 'port'
		},{
			fieldLabel: t.texts.databaseName,
			name: 'database'
		},{
			fieldLabel: t.texts.user,
			name: 'user'
		},{
			inputType: 'password',
			fieldLabel: t.texts.password,
			name: 'password',
			allowBlank: true
		},{
			fieldLabel: t.texts.url,
			name: 'url',
			allowBlank: true,
			readOnly: true
//			hidden: true,
//			hideLabel: true
		}];
		t.buttons=[{
			text: wsc.Messages.ok,
			handler: function(b){
				var fieldLabel = t.checkValues();
				if(!fieldLabel){
					t.fireEvent('ok', t, t.getValues());
				}else{
					Ext.Msg.alert(wsc.Messages.infoMessage, wsc.Messages.fieldRequired+fieldLabel);
				}
			}
		},{
			text: wsc.Messages.cancel,
			handler: function(b){
				t.close();
			}
		}];
		wsc.DatabaseConfigWindow.superclass.initComponent.call(this);
	},
	setValues:function(values){
		var its = this.items;
		var count = its.getCount();
		for(var i=0;i<count;i++){
			var it = its.itemAt(i);
			if(it.name&&values[it.name])it.setValue(values[it.name]);
			else if(it.name)it.setValue('');
		}
	},
	getValues:function(){
		var p = {};
		var its = this.items;
		var count = its.getCount();
		for(var i=0;i<count;i++){
			var it = its.itemAt(i);
			if(it.name)p[it.name]=it.getValue();
		}
		return p;
	},
	checkValues:function(){
		var its = this.items;
		var count = its.getCount();
		for(var i=0;i<count;i++){
			var it = its.itemAt(i);
			if(it.allowBlank==false&&(!it.getValue()||it.getValue()==0||(typeof it.getValue()=='string'&&it.getValue().trim()==''))){it.focus();return it.fieldLabel};
		}
		return false;
	},
	changeDBType: function(database){
		var vs = {};
		vs.host='127.0.0.1';
		vs.driver=database.driver,
		vs.port=database.port;
		vs.database=database.database;
		vs.user=database.user;
		vs.url=database.url;
		if(this.urlTpl)
			this.urlTpl = new Ext.XTemplate(database.url);
		this.setValues(vs);
	},
	texts: {
		configName: 'Config Name',
		databaseType: 'Server Type',
		driverClass: 'Driver Class',
		host: 'Host',
		port: 'Port',
		databaseName: 'Database Name',
		user: 'User Name',
		password: 'Password',
		url: 'Connection URL'
	}
});

wsc.DBConnectionTreePanel = Ext.extend(Ext.Panel, {
	initComponent: function(){
		var t = this;
		t.createTBar();
		t.layout='fit';
		t.createDBConnectionTree();
		wsc.DBConnectionTreePanel.superclass.initComponent.call(this);
	},
	createTBar: function(){
		var t = this;
		t.tbar = new Ext.Toolbar();
		var handler = function (button, event){
			var node = t.treePanel.getSelectionModel().getSelectedNode();
			if(node&&node.attributes[button.action])
				node.attributes[button.action](node);
			else if(!node){
				Ext.Msg.alert('提示信息','请选择相应结点');
			}
		};
		t.addButton = t.tbar.addButton({
			text: t.texts.add,
			iconCls: 'addButton',
			handler: handler,
			action: 'addHandler'
		});
		t.delButton = t.tbar.addButton({
			text: t.texts.del,
			iconCls: 'delButton',
			handler: handler,
			action: 'delHandler'
		});
		t.chanageButton = t.tbar.addButton({
			text: t.texts.change,
			iconCls: 'editButton',
			handler: handler,
			action: 'changeHandler'
		});
	},
	getDrivers : function(){
		var t=this;
		var cs=t.driverNode.childNodes;
		var reValue={};
		for(var i=0;i<cs.length;i++){
			reValue[cs[i].text]=cs[i].attributes;
		}
		return reValue;
	},
	createDBConnectionTree: function(){
		var root = new Ext.tree.TreeNode({});
		var t = this;
		t.rootNode = root;
		t.treePanel = new Ext.tree.TreePanel({
			rootVisible: false,
			root: t.rootNode
		});
		t.items=[t.treePanel];
		t.connectionNode = root.appendChild(t.createNode(t.texts.connections));
		t.configNode = root.appendChild(t.createNode(t.texts.configs,function(node){
			var win = new wsc.DatabaseConfigWindow({
				sqlManager: t.sqlManager,
				listeners: {
					ok: function(w, values){
						var atts = node.attributes;
						alert(values.url);
						var tpl = new Ext.XTemplate(values.url);
						alert(tpl.applyTemplate(values));
						t.configNode.appendChild(t.createNode(values.name));
						t.configNode.expand();
					}
				}
			});
			win.show();
		}));
		t.driverNode = root.appendChild(t.createNode(t.texts.drivers, function(node){
			var win = new wsc.DatebaseDriverWindow({
				sqlManager: t.sqlManager,
				listeners: {
					beforeok: function(win, values){
						if(node.findChild('text', values.name)){
							Ext.Msg.alert(wsc.Messages.infoMessage, String.format(t.texts.driverNameHas,values.name));
							return true;
						}
						return false;
					},
					ok: function(win, values){
						values.text = values.name;
						values.leaf = true;
						values.expandable = false;
						node.appendChild(t.createNode(values,undefined,function(node){node.remove();},function(node){
							var win = new wsc.DatebaseDriverWindow({
								listeners: {
									beforeok: function(win, values){
										if(t.driverNode.findChild('text', values.name)){
											Ext.Msg.alert(wsc.Messages.infoMessage, String.format(t.texts.driverNameHas,values.name));
											return true;
										}
										return false;
									},
									ok: function(win, values){
										values.text=values.name;
										Ext.apply(node.attributes, values);
										node.setText(values.name);
										win.close();
									}
								}
							});
							win.setValues(node.attributes);
							win.show();
						}));
						win.close();
						node.expand();
					}
				}
			});
			win.show();
		}));
		t.initDefaultDrivers();
	},
	initDefaultDrivers: function(){
		var t=this;
		if(wsc.defaultDrivers){
			var defFun = function(node){node.remove();};
			var chanFun = function(node){
				var win = new wsc.DatebaseDriverWindow({
					sqlManager: t.sqlManager,
					listeners: {
						beforeok: function(win, values){
							if(t.driverNode.findChild('text', values.name)){
								Ext.Msg.alert(wsc.Messages.infoMessage, String.format(t.texts.driverNameHasExist,values.name));
								return true;
							}
							return false;
						},
						ok: function(win, values){
							values.text=values.name;
							Ext.apply(node.attributes, values);
							node.setText(values.name);
							win.close();
						}
					}
				});
				win.setValues(node.attributes);
				win.show();
			};
			for(var i=0;i<wsc.defaultDrivers.length;i++){
				t.driverNode.appendChild(t.createNode(
					wsc.defaultDrivers[i],
					undefined,
					defFun,
					chanFun
				));
			}
		}
	},
	createNode:function(text, addHandler, delHandler, changeHandler){
		var obj = typeof text=='object'?text:{};
		if(typeof text=='object')text=text.text;
		var conf = {
			text:text,
			allowChildren:true,
			expandable:true,
			addHandler:addHandler,
			delHandler:delHandler,
			changeHandler:changeHandler
		};
		conf = Ext.apply(conf, obj);
		return new Ext.tree.TreeNode(conf);
	},
	texts: {
		add: 'Add',
		del: 'Del',
		change: 'Change',
		connections: 'Connections',
		configs: 'Configs',
		drivers: 'Drivers',
		driverNameHasExist: 'Driver Name "{0}" has Exits'
	}
});
wsc.getDriverStore = function(sqlManager){
	if(!wsc.getDriverStore.store){
		wsc.getDriverStore.store = DataStore({
			fields: ['name', 'driverConfig'],
			idIndex: 0
		});
	}
	var s = wsc.getDriverStore.store;
	s.clearData();
	var ds = sqlManager.dbConPanel.getDrivers();
	for(var p in ds){
		s._data.push([p, ds[p]]);
	}
	s.reload();
	return wsc.getDriverStore.store;
};
wsc.Manager = Ext.extend(Ext.Panel, {
	border: false,
	initComponent: function() {
		var t = this;
		t.layout = 'border';
		t.dbConPanel = new wsc.DBConnectionTreePanel({
			region: 'west',
			title: t.texts.dbConnections,
			width: 220,
			collapsible: true,
			sqlManager: t
		});
		t.mainTabPanel = new Ext.TabPanel({
			region: 'center',
			xtype: 'tabpanel',
			sqlManager: t
		});
		t.items=[t.dbConPanel, t.mainTabPanel];
		wsc.Manager.superclass.initComponent.call(this);
	},
	texts: {
		dbConnections: 'Database Connections'
	}
});
